package com.pap.oauth.authentication.mobile;

import com.pap.oauth.authentication.mobile.config.security.MobileUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

/**
 * 短信登录验证逻辑
 *
 * SmsCodeAuthenticationProvider对应用户名密码登录的DaoAuthenticationProvider
 *
 */
@Deprecated
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private MobileUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;

        //调用自定义的userDetailsService认证
        UserDetails user = userDetailsService.loadUserByMobileAndSmsCode((String) authenticationToken.getPrincipal(), (String) authenticationToken.getCredentials());

        if (user == null || StringUtils.isEmpty(user.getUsername())) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        //如果user不为空重新构建SmsCodeAuthenticationToken（已认证）
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, null, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * 只有Authentication为SmsCodeAuthenticationToken使用此Provider认证
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public MobileUserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(MobileUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
